//ipPort = '10.58.89.1:9090';
//ipPort = '10.58.88.212:8080';
a_fail = 0;
a_succ = 0;

Ext.define('Case.Resport',{
	extend: 'Ext.panel.Panel',
	alias: 'case.report',
	
	optimizeDate: function(node){
		// changes the date back to a readable format, as it was changed for sorting 
		var date = node.data.date;
		if (date == '99999999999999'){
			node.data.date = 'n/a';
			return;
		};
		var year = date.substring(0,4);
		var month = date.substring(4,6);
		var day = date.substring(6,8);
		var hour = date.substring(8,10);
		var minute = date.substring(10,12);
		node.data.date = year + '-' + month + '-' + day + ', ' + hour + ':' + minute;
	},
	
	finishNode: function(node){
		// Sets icon and bar for each node; same coding for product-, catalog- and testcasenode.
		// A chart can't be inserted into a table, therefore I worked with png-files
		var bar = '';
   		var sum = node.data.succ + node.data.fail;
   		var one = 200 / sum; // 200px is the width of the column
   		// rounding is necessary to make all bars same width
   		succ_length = Math.round(one * node.data.succ);
   		fail_length = Math.round(one * node.data.fail);
   		if (succ_length !== 0){
   			bar = "<img src='icons/green.png' width=" + succ_length + " height='100%'>";
   		};
   		if (fail_length !== 0){
   			bar = bar + "<img src='icons/red.png' width=" + fail_length + " height='100%'>";
   		};
   		node.data.bar = bar;
   		// set icons:
   		if ((node.data.succ > 0) && (node.data.fail == 0)){
   			node.data.resultIcon = "<img src='icons/ok.gif'>";
   		} else {
   			node.data.resultIcon = "<img src='icons/fail.gif'>";
   		};
	},
	
	createSubCaseNodes: function(testCaseId, productNode, tree, numberOfCatalogs, numberOfCases){
		// creates subcasenodes for each testcasenode
		// wsCount is necessary to call some coding after every webservice answered
		// it's increased everytime before a webservice is called and is decreased in the callback function of a webservice
		wsCount++; 
//		subCaseNamesReport = new Array;
//		steps = new Array;
//		params = new Array;
		
		Ext.Ajax.request({
			url: 'http://' + ipPort + '/bpccase/' + testCaseId,
			method: 'GET',
			success: function(response){
				var obj = Ext.decode(response.responseText);
				var tCaseId = obj.id;
				var testCaseNode = productNode.findChildBy(function(){ // function to find testCaseNode for current subCase
					if (this.data.id == ('t' + tCaseId)) return true;
				}, productNode.children, true);
				testCaseData[tCaseId] = obj;
				if (!(testCaseData[tCaseId].subcases)) alert('missing data');
				if (testCaseData[tCaseId].subcases.length){
					numberOfSubCases[tCaseId] = testCaseData[tCaseId].subcases.length;
				} else {
					numberOfSubCases[tCaseId] = 1;
				};
				if (testCaseData[tCaseId].steps.length){
					numberOfSteps[tCaseId] = testCaseData[tCaseId].steps.length;
				} else {
					numberOfSteps[tCaseId] = 1;
				};
				
				wsCount++;
				Ext.Ajax.request({
					url: 'http://' + ipPort + '/bpclastresults/' + tCaseId + '/0',
					method: 'GET',
					success: function(response){
						var tCId = tCaseId;
						testCaseResult[tCId] = Ext.decode(response.responseText);
						if (!(testCaseResult[tCId].Result[0])){
							me_report.addLogEntry("Missing testdata in " + testCaseData[tCId].name + " with ID " + tCId);
							return;
						}
						if (!(testCaseResult[tCId].Result[0].date)){
							me_report.addLogEntry("Error in " + testCaseData[tCId].name);
							return;
						}
						var loopCount = 0;
						for (i = 0; i < numberOfSubCases[tCId]; i++){
							if (numberOfSubCases[tCId] == 1){
								var subCaseName = testCaseData[tCId].subcases.name;
								var subCaseId = testCaseData[tCId].subcases.id;
							} else {
								var subCaseName = testCaseData[tCId].subcases[i].name;
								var subCaseId = testCaseData[tCId].subcases[i].id;
							};
							if (!(testCaseResult[tCId].Result[loopCount].date)){
								alert("Error in SubCase " + subCaseName);
								break;
							}
							var testDate = testCaseResult[tCId].Result[loopCount].date;
							date = testDate.substring(0,10); 
    						time = testDate.substring(11,19);
    						dateArray = date.split('-');
    						timeArray = time.split(':')
    						date = dateArray.join('') + timeArray.join('');
								for (j = 0; j < numberOfSteps[tCId]; j++){
									if (numberOfSteps[tCId] == 1){
										var expResponse = testCaseData[tCId].steps.response;
									} else {
										var expResponse = testCaseData[tCId].steps[j].response;
									};
									var response = testCaseResult[tCId].Result[loopCount].response;
									
									// insert param values into expected response
									if (numberOfSubCases[tCId] == 1){
										if (testCaseData[tCId].subcases.params){
											if (testCaseData[tCId].subcases.params.length){
												var params = testCaseData[tCId].subcases.params;
												var numberOfParams = params.length;
												for (k = 0; k < numberOfParams; k++){
													var paramName = params[k].name;
													var splitter = '<%' + paramName + '%>';
													var paramValue = params[k].value;
													var expResponseArray = new Array;
													expResponseArray = expResponse.split(splitter);
													expResponse = expResponseArray.join(paramValue);
												};
											} else {
												var numberOfParams = 1;
												var paramName = testCaseData[tCId].subcases.params.name;
												var splitter = '<%' + paramName + '%>';
												var paramValue = testCaseData[tCId].subcases.params.value;
												expResponseArray = expResponse.split(splitter);
												expResponse = expResponseArray.join(paramValue);
											};
										};
									} else {
										if (testCaseData[tCId].subcases[i].params){
											if (testCaseData[tCId].subcases[i].params.length){
												var params = testCaseData[tCId].subcases[i].params;
												var numberOfParams = params.length;
												for (k = 0; k < numberOfParams; k++){
													var paramName = params[k].name;
													var splitter = '<%' + paramName + '%>';
													var paramValue = params[k].value;
													var expResponseArray = new Array;
													expResponseArray = expResponse.split(splitter);
													expResponse = expResponseArray.join(paramValue);
												};
											} else {
												var numberOfParams = 1;
												var paramName = testCaseData[tCId].subcases[i].params.name;
												var splitter = '<%' + paramName + '%>';
												var paramValue = testCaseData[tCId].subcases[i].params.value;
												expResponseArray = expResponse.split(splitter);
												expResponse = expResponseArray.join(paramValue);
											};
										};
									}
									if (response == expResponse){
										result = 'ok';
									} else {
										result = 'fail';
										break;
									}
									
									loopCount ++;
								};
								testCaseNode.appendChild({ // append subcasenode
	    							path: subCaseName,
	    							id: 's' + subCaseId,
	    							leaf: 'true',
	    							resultIcon: "<img src='icons/" + result + ".gif'>",
	    							date: date,
	    							succ: 0,
	    							fail: 0,
	    							bar: ''
	    						});
	    						subCaseNode = testCaseNode.lastChild;
	    						if (result == 'ok'){ // increase counter of successful cases
	    							subCaseNode.data.succ++;
	    							testCaseNode.data.succ++;
	    							productNode.data.succ++;
	    							testCaseNode.parentNode.data.succ++;    							
	    						} else if (result == 'fail'){ // increase counter of failed cases
	    							subCaseNode.data.fail++;
	    							testCaseNode.data.fail++;
	    							productNode.data.fail++;
	    							testCaseNode.parentNode.data.fail++;  
	    						}; 
	    						// set icons and bars for all nodes: 
	    						me_report.finishNode(subCaseNode);
	    			       		me_report.finishNode(testCaseNode);
	    			       		me_report.finishNode(testCaseNode.parentNode);
	    			       		me_report.finishNode(productNode);
	    			       		// set the oldest date as the last test date:
	    			       		if (testCaseNode.data.date > date){
	    			       			testCaseNode.data.date = date;
	    			       		};
	    			       		if (testCaseNode.parentNode.data.date > date){
	    			       			testCaseNode.parentNode.data.date = date;
	    			       		};
	    			       		if (productNode.data.date > date){
	    			       			productNode.data.date = date;
	    			       		};
						}
					},
					failure: function(){
						
					},
					callback: function(){
						wsCount--;
						if (wsCount == 0){
//							 change date format for all nodes:
							me_report.optimizeDate(productNode);
							productNode.eachChild( //catalogNodes
								function(cn){
									me_report.optimizeDate(cn);
									cn.eachChild( //testCaseNodes
										function(tn){
											me_report.optimizeDate(tn);
											tn.eachChild( //subCaseNodes
												function(sn){
													me_report.optimizeDate(sn);
												}	
											);
										}
									);
								}
							);
							tree.expandAll(); // necessary for updating the data in the tree
							me_report.setVisible(true);
							reportWin.setLoading(false);
						};
					}
				})
				
			},
			failure: function(){
				
			},
			callback: function(){
				wsCount--;
				if (wsCount == 0){
//					 change date format for all nodes:
					me_report.optimizeDate(productNode);
					productNode.eachChild( //catalogNodes
						function(cn){
							me_report.optimizeDate(cn);
							cn.eachChild( //testCaseNodes
								function(tn){
									me_report.optimizeDate(tn);
									tn.eachChild( //subCaseNodes
										function(sn){
											me_report.optimizeDate(sn);
										}	
									);
								}
							);
						}
					);
					tree.expandAll(); // necessary for updating the data in the tree
					me_report.setVisible(true);
					reportWin.setLoading(false);
				};
			}
		});

	},
	
	initComponent: function(){
		testCaseData = new Array;
		testCaseResult = new Array;
		numberOfSubCases = new Array;
		numberOfSteps = new Array;
		me_report = this;
		// wsCount is necessary to call some coding after every webservice answered
		// it's increased everytime before a webservice is called and is decreased in the callback function of a webservice
		wsCount = 0;
		var tree = Ext.create('Ext.tree.Panel', {
			width: '100%',
			height: '300',
			rootVisible: true,
//			hidden: true, // tree is first shown, after all data is loaded
			root: {
				path: "BPC 10 NW API Test Cases",
				succ: 0,
				fail: 0,
				date: 99999999999999 // has to be a higher value than every possible date (for sorting)
			},
			columns:[{
				xtype: 'treecolumn',
				text: 'Catalog/Testcase/Subcase',
				dataIndex: 'path',
				flex: 22
			},{
				text: '',
				dataIndex: 'resultIcon',
				flex: 2
			},{
				text: 'Success',
				dataIndex: 'succ',
				flex: 5
			},{
				text: 'Fail',
				dataIndex: 'fail',
				flex: 5
			},{
				text: '',
				dataIndex: 'bar',
				width: 200 // exact width necessary for bar
//				flex: 18
			},{
				text: 'Date of last test',
				dataIndex: 'date',
				flex: 16
			}]
		});
		
		tree.on('itemdblclick', this.onDblClick, this);
		var productNode = tree.getRootNode();
		wsCount++;
		Ext.Ajax.request({ 
			url: 'http://' + ipPort + '/bpccasestree',
			method: 'GET',
			success: function(response){
				var obj = Ext.decode(response.responseText);
				var numberOfCatalogs = obj.Catalog.length;
				for (i = 0; i < numberOfCatalogs; i++){
						// append catalog nodes
						var catalogName = obj.Catalog[i].name;
						var catalogId = obj.Catalog[i].id;
						productNode.appendChild({
							path: catalogName,
							id: 'c' + catalogId,
							succ: 0,
							fail: 0,
							date: 99999999999999 // has to be a higher value than every possible date (for sorting)
						});
						if (obj.Catalog[i].cases){
							if (obj.Catalog[i].cases.length) {
								var numberOfCases = obj.Catalog[i].cases.length;
							} else {
								// no array, if only one testcase
								var numberOfCases = 1;
							}
							for (j = 0; j < numberOfCases; j++){
								if (numberOfCases == 1){ // no array
									// append subCaseNodes
									var testCaseName = obj.Catalog[i].cases.name;
									var testCaseId = obj.Catalog[i].cases.id;
									var catalogIdForCase = obj.Catalog[i].cases.catalogId;
									// find catalognode, necessary due to asynchronous calling of webservices
									var catalogNode = productNode.findChildBy(function(){ 
										if (this.data.id == ('c' + catalogIdForCase)) return true;
										}, productNode.children, true);
									catalogNode.appendChild({
										path: testCaseName,
										id: 't' + testCaseId,
										succ: 0,
										fail: 0,
										date: 99999999999999 // has to be a higher value than every possible date (for sorting)
									});
									me_report.createSubCaseNodes(testCaseId, productNode, tree);
								} else { // array
									// append subCaseNodes
									var testCaseName = obj.Catalog[i].cases[j].name;
									var testCaseId = obj.Catalog[i].cases[j].id;
									var catalogIdForCase = obj.Catalog[i].cases[j].catalogId;
									// find catalognode, necessary due to asynchronous calling of webservices
									var catalogNode = productNode.findChildBy(function(){
										if (this.data.id == ('c' + catalogIdForCase)) return true;
										}, productNode.children, true);
									catalogNode.appendChild({
										path: testCaseName,
										id: 't' + testCaseId,
										succ: 0,
										fail: 0,
										date: 99999999999999 // has to be a higher value than every possible date (for sorting)
									});
									me_report.createSubCaseNodes(testCaseId, productNode, tree, numberOfCatalogs, numberOfCases);
								};
							};
						};
				};
			},
			failure: function() {
	
			},
			callback: function() {
				wsCount--;
				if (wsCount == 0){
//					 change date format for all nodes:
					me_report.optimizeDate(productNode);
					productNode.eachChild( //catalogNodes
						function(cn){
							me_report.optimizeDate(cn);
							cn.eachChild( //testCaseNodes
								function(tn){
									me_report.optimizeDate(tn);
									tn.eachChild( //subCaseNodes
										function(sn){
											me_report.optimizeDate(sn);
										}	
									);
								}
							);
						}
					);
					tree.doLayout();
					tree.expandAll(); // necessary for updating the data in the tree
					me_report.setVisible(true);
					reportWin.setLoading(false);
				};
			}
		});
		
   
		Ext.apply(me_report, {
			// main panel
			closable: false,
			frame: false,
			width: '100%',
			height: '100%',
			layout: 'border',
			items: [{
				// header panel
				xtype: 'container',
				region: 'north',
				width: '100%',
				height: '5%',
				layout: 'border',
				items: [{
					// product information
					xtype: 'container',
					region: 'center',
					width: 600,
					flex: 5,
					items: [{
						xtype: 'displayfield',
						id: 'productName',
						value: "Report for BPC 10 NW API Test Cases - Doubleclick a SubCase to see details."
					}]
				},{
					// panel for chart
					xtype: 'container',
					region: 'east',
					flex: 1
				}]
			},{
				// treepanel
				xtype: 'container',
				region: 'center',
			//	height: '600',
				id: 'treePanel',
				items: [tree]
			},{
				xtype: 'container',
				region: 'south',
				id: 'logpanel',
				height: '20%',
				title: 'Log',
				autoscroll: true,
				items: [{
					xtype: 'displayfield',
					value: 'Log:'
				}]
			}]
		});
		
		me_report.callParent(arguments);
		
	},
	
	addLogEntry: function(message){
		var entry = Ext.create(Ext.form.field.Display, {
			value: message
		});
		var logPanel = me_report.getComponent('logpanel');
		logPanel.add(entry);
	},
	
	onDblClick: function(view, rec, node, idx, e){
		// open resultscreen for subcase by doubleclicking on it
		if (rec.get('leaf')){
		reportWin.setLoading('Loading Details');
		
			// get subcaseid and testcaseid (cut off first letter, it's added for unique ids in tree)
			var sid = rec.get('id');
			var subCaseId = sid.substring(1, sid.length);
			var subCaseName = rec.get('path');
			var cid = rec.parentNode.data.id;
			var caseId = cid.substring(1, cid.length);
			// the resultscreen needs both testcaseData and subCaseData
			// here no increase of wsCount, because this webservice can only be called if report is already loaded
			var url = 'http://' + ipPort + '/bpclastresults/0/' + subCaseId;
			caseData = null;
			Ext.Ajax.request({ 
				url: url,
				method: 'GET',
				success: function(response){
					var obj = Ext.decode(response.responseText);
					// here no increase of wsCount, because this webservice can only be called if report is already loaded
					var url = 'http://' + ipPort + '/bpccase/' + caseId;
					Ext.Ajax.request({ 
						url: url,
						method: 'GET',
						success: function(response){
							var caseData = Ext.decode(response.responseText);
							var resultUI = Ext.create('case.result',{obj: obj, caseData: caseData, subCaseName: subCaseName});
    							resultWin = Ext.create('Ext.window.Window', {
    							title: 'Result',
    							closable: true,
//    							animateTarget: me_report,
    							width: 800,
    							height: 600,
    							borderStyle: 'padding:5px;',
    							shadown: false,
    							modal: true,
    							items: [
    								resultUI
    							]
    						});
    						resultWin.show(this, function(){
    						});
						},
						failure: function() {
						},
						callback: function() {
							reportWin.setLoading(false);
							me_report.setLoading(false);
						}
					});    						
				},
				failure: function() {
				},
				callback: function() {
					
					
					
				}
			});
		};
	}
});